package com.blog.cloud.auth.oauth.request;

import com.alibaba.fastjson.JSONObject;
import com.blog.cloud.auth.oauth.cache.AuthDefaultSource;
import com.blog.cloud.auth.oauth.cache.AuthStateCache;
import com.blog.cloud.auth.oauth.config.AuthConfig;
import com.blog.cloud.auth.oauth.enums.AuthResponseStatus;
import com.blog.cloud.auth.oauth.enums.AuthUserGender;
import com.blog.cloud.auth.oauth.exception.AuthException;
import com.blog.cloud.auth.oauth.model.AuthCallback;
import com.blog.cloud.auth.oauth.model.AuthResponse;
import com.blog.cloud.auth.oauth.model.AuthToken;
import com.blog.cloud.auth.oauth.model.AuthUser;
import me.zhyd.oauth.utils.AuthScopeUtils;
import me.zhyd.oauth.utils.GlobalAuthUtils;
import me.zhyd.oauth.utils.HttpUtils;
import me.zhyd.oauth.utils.UrlBuilder;

public class AuthWeChatMpRequest extends AuthDefaultRequest {
    public AuthWeChatMpRequest(AuthConfig config) {
        super(config, AuthDefaultSource.WECHAT_MP);
    }

    public AuthWeChatMpRequest(AuthConfig config, AuthStateCache authStateCache) {
        super(config, AuthDefaultSource.WECHAT_MP, authStateCache);
    }

    @Override
    protected AuthToken getAccessToken(AuthCallback authCallback) {
        return this.getToken(this.accessTokenUrl(authCallback.getCode()));
    }

    @Override
    protected AuthUser getUserInfo(AuthToken authToken) {
        String openId = authToken.getOpenId();
        String response = this.doGetUserInfo(authToken);
        JSONObject object = JSONObject.parseObject(response);
        this.checkResponse(object);
        String location = String.format("%s-%s-%s", object.getString("country"), object.getString("province"), object.getString("city"));
        if (object.containsKey("unionid")) {
            authToken.setUnionId(object.getString("unionid"));
        }
        return AuthUser.builder()
                .rawUserInfo(object)
                .username(object.getString("nickname"))
                .nickname(object.getString("nickname"))
                .avatar(object.getString("headimgurl"))
                .location(location)
                .uuid(openId)
                .gender(AuthUserGender.getWechatRealGender(object.getString("sex")))
                .token(authToken)
                .source(this.source.toString())
                .build();
    }

    @Override
    public AuthResponse<Object> refresh(AuthToken oldToken) {
        return AuthResponse.builder()
                .code(AuthResponseStatus.SUCCESS.getCode())
                .data(this.getToken(this.refreshTokenUrl(oldToken.getRefreshToken())))
                .build();
    }

    @Override
    public String authorize(String state) {
        return UrlBuilder.fromBaseUrl(this.source.authorize()).queryParam("appid", this.config.getClientId()).queryParam("redirect_uri", GlobalAuthUtils.urlEncode(this.config.getRedirectUri())).queryParam("response_type", "code").queryParam("scope", this.getScopes(",", false, AuthScopeUtils.getDefaultScopes(AuthWechatMpScope.values()))).queryParam("state", this.getRealState(state).concat("#wechat_redirect")).build();
    }

    private void checkResponse(JSONObject object) {
        if (object.containsKey("errcode")) {
            throw new AuthException(object.getIntValue("errcode"), object.getString("errmsg"));
        }
    }

    private AuthToken getToken(String accessTokenUrl) {
        String response = (new HttpUtils(this.config.getHttpConfig())).get(accessTokenUrl);
        JSONObject accessTokenObject = JSONObject.parseObject(response);
        this.checkResponse(accessTokenObject);
        return AuthToken.builder()
                .accessToken(accessTokenObject.getString("access_token"))
                .refreshToken(accessTokenObject.getString("refresh_token"))
                .expireIn(accessTokenObject.getIntValue("expires_in"))
                .openId(accessTokenObject.getString("openid"))
                .scope(accessTokenObject.getString("scope"))
                .build();
    }

    protected String accessTokenUrl(String code) {
        return UrlBuilder.fromBaseUrl(this.source.accessToken()).queryParam("appid", this.config.getClientId()).queryParam("secret", this.config.getClientSecret()).queryParam("code", code).queryParam("grant_type", "authorization_code").build();
    }

    protected String userInfoUrl(AuthToken authToken) {
        return UrlBuilder.fromBaseUrl(this.source.userInfo()).queryParam("access_token", authToken.getAccessToken()).queryParam("openid", authToken.getOpenId()).queryParam("lang", "zh_CN").build();
    }

    protected String refreshTokenUrl(String refreshToken) {
        return UrlBuilder.fromBaseUrl(this.source.refresh()).queryParam("appid", this.config.getClientId()).queryParam("grant_type", "refresh_token").queryParam("refresh_token", refreshToken).build();
    }
}
